package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.HemaUtil;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.LaokeReplyAdapter;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImageItem;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.ReplyItemClickListener;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;

/**唠嗑帖子详情
 * 后来更名为助农帖子详情
 * @author ZhangGuiyou
 * Date: 2015-08-19 13:05
 *
 */
public class LaokeDetailActivity extends BaseActivity implements OnClickListener, ReplyItemClickListener{
	
	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRight;
	private ImageView titleRightImg;
	
	private RefreshLoadmoreLayout layoutRefresh;
	private View headerView;
	private XtomListView listview;
	private LinearLayout ll_return_top;
	private LinearLayout layout_zan;
	private TextView tvZan;
	private LinearLayout layout_comment;
	private TextView tvComment;

	ImageView iv_avatar;
	TextView tv_name;
	TextView tv_date;
	TextView tv_title;
	TextView tv_content;
	TextView tv_reply_num;
	LinearLayout ll_container;

	private User user;
	private Blog blog;
	private String blog_id;
	private LaokeReplyAdapter adapter;
	private ArrayList<Reply> replies = new ArrayList<Reply>();
	private Reply reply;//用于跟楼回复时使用
	private Reply delReply;//用于删除回复
	private int page = 0;
	private int goodCount = 0;//点赞数量
    private LoginUtil.LoginCallBack loginCallBack;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_blog_detail);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
		init();
	}
	
	private void init() {
		//初始化listivew的header部分
		headerView = LayoutInflater.from(mContext).inflate(R.layout.header_laoke_detail, null);
		findHeaderViews();
		listview.addHeaderView(headerView);

		if (blog == null && blog_id != null) {
			String token = "";
			if (user != null) {
				token = user.getToken();
			}
			getNetWorker().blogGet(token, blog_id);
		}else if (blog != null) {
			setData();
			getReply();//获取评论
		}
	}
	
	/**获取唠嗑回复列表
	 * 
	 */
	private void getReply() {
		if (blog != null) {
			getNetWorker().replyList("2", blog.getId(), page+"");
		}
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
            case BLOG_GET:
            case REPLY_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
            case REPLY_LIST:
            case BLOG_GET:
                cancelProgressDialog();
                break;
        }
    }

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case BLOG_GET:
			HemaArrayResult<Blog> bResult = (HemaArrayResult<Blog>) baseResult;
			blog = bResult.getObjects().get(0);
			if (blog == null) {
				showTextDialog("获取信息失败！");
				titleText.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						finish();
					}
				}, 2000);
			}else {
				setData();
				getReply();//获取评论
			}
			break;
		case REPLY_LIST:
			String page = netTask.getParams().get("page");
			HemaPageArrayResult<Reply> nResult = (HemaPageArrayResult<Reply>) baseResult;
			if (nResult == null || nResult.getObjects() == null)
				return;
			ArrayList<Reply> replies = nResult.getObjects();
			if ("0".equals(page)) {// 刷新
				layoutRefresh.refreshSuccess();
				this.replies.clear();
				this.replies.addAll(replies);
				listview.smoothScrollToPosition(0);
			} else {// 更多
				layoutRefresh.loadmoreSuccess();
				if (replies.size() > 0)
					this.replies.addAll(replies);
				else {
					layoutRefresh.setLoadmoreable(false);
					XtomToastUtil.showShortToast(mContext, "已经到最后啦");
				}
			}
			refreshData(-1);
			break;
		case BLOG_SAVEOPERATE:
			XtomToastUtil.showShortToast(mContext, "删除成功");
			titleText.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					setResult(RESULT_OK);
					finish();
				}
			}, 1500);
			break;
		case FOLLOW_COLLECT_SAVEOPERATE:
			String oper = netTask.getParams().get("oper");
            //通知唠嗑列表刷新
            EventBusMsg msg = new EventBusMsg();
            msg.setType(EventBusConfig.UPDATE_BLOG);
            EventBus.getDefault().post(msg);
            //刷新本页
			View view = mContext.getLayoutInflater().inflate(R.layout.pop_zan,
					null);
			TextView textview = (TextView) view.findViewById(R.id.textview);
			if (oper.equals("1")) {//点赞操作
				textview.setText("+1");
				blog.setGoodflag("1");
				goodCount++;
				tvZan.setText(goodCount+"");
				tvZan.setCompoundDrawablesWithIntrinsicBounds(
						mContext.getResources().getDrawable(R.drawable.thumbs_up_orange), null, null, null);
			}else if (oper.equals("2")) {//取消点赞
				textview.setText("-1");
				blog.setGoodflag("0");
				goodCount--;
				tvZan.setText(goodCount+"");
				tvZan.setCompoundDrawablesWithIntrinsicBounds(
						getResources().getDrawable(R.drawable.thumbs_up_grey), null, null, null);
			}
			final PopupWindow pop = new PopupWindow(view, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);
			pop.setOutsideTouchable(true);
			pop.setFocusable(true);
			pop.showAsDropDown(findViewById(R.id.title_text));
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					pop.dismiss();
				}
			}, 1000);
			break;
		case REPLY_REMOVE:
			for (Reply reply : this.replies) {
				if (delReply.getId().equals(reply.getId())) {
					this.replies.remove(reply);
					refreshData(-1);
					break;
				}
			}
			try{
				int count = Integer.parseInt(tvComment.getText().toString());
				tv_reply_num.setText(count-1+"");
				tvComment.setText(count-1+"");
			}catch(Exception e) {
				e.printStackTrace();
			}
            //通知唠嗑列表刷新
            EventBusMsg msg1 = new EventBusMsg();
            msg1.setType(EventBusConfig.UPDATE_REPLY_REMOVE);
            EventBus.getDefault().post(msg1);
			break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case BLOG_GET:
			showTextDialog("获取信息失败！");
			titleText.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					finish();
				}
			}, 2000);
			break;
		case REPLY_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				layoutRefresh.refreshFailed();
			}else {
				layoutRefresh.loadmoreFailed();
			}
			showTextDialog(baseResult.getMsg());
			break;
		case REPLY_ADD:
		case BLOG_SAVEOPERATE:
		case FOLLOW_COLLECT_SAVEOPERATE:
		case REPLY_REMOVE:
			XtomToastUtil.showShortToast(mContext, "操作失败,"+baseResult.getMsg());
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case BLOG_GET:
			showTextDialog("获取信息失败！");
			titleText.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					finish();
				}
			}, 2000);
		case REPLY_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				layoutRefresh.refreshFailed();
			}else {
				layoutRefresh.loadmoreFailed();
			}
			refreshData(failedType);
			break;
		case REPLY_ADD:
		case BLOG_SAVEOPERATE:
		case FOLLOW_COLLECT_SAVEOPERATE:
		case REPLY_REMOVE:
			XtomToastUtil.showShortToast(mContext, "操作失败!");
			break;
		default:
			break;
		}
	}

	private void refreshData(int failedType) {
		if (adapter == null) {
			adapter = new LaokeReplyAdapter(mContext, replies);
			adapter.setEmptyString("暂无评论");
            adapter.setItemClickListener(this);
			listview.setAdapter(adapter);
		}else {
			adapter.notifyDataSetChanged();
		}
		adapter.setFailtype(failedType);
	}

	@Override
	protected void getExras() {
		blog = (Blog) getIntent().getSerializableExtra("blog");
		blog_id = mIntent.getStringExtra("blog_id");
		if (blog!=null&&isNull(blog_id)) {
			blog_id = blog.getId();
		}
	}

	@Override
	protected void findView() {
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleRight = (Button) findViewById(R.id.title_right_btn);
		titleRightImg = (ImageView) findViewById(R.id.title_right_img);

		layoutRefresh = (RefreshLoadmoreLayout)findViewById( R.id.layout_refresh );
		listview = (XtomListView)findViewById( R.id.listview );
		ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部
		tvZan = (TextView)findViewById( R.id.tv_zan );
		tvComment = (TextView)findViewById( R.id.tv_comment );
		layout_comment = (LinearLayout) findViewById(R.id.layout_comment);
		layout_zan = (LinearLayout) findViewById(R.id.layout_zan);
	}
	
	private void findHeaderViews() {
		iv_avatar = (ImageView) headerView.findViewById(R.id.avatar);
		tv_name = (TextView) headerView.findViewById(R.id.tv_name);
		tv_date = (TextView) headerView.findViewById(R.id.tv_date);
		tv_title = (TextView) headerView.findViewById(R.id.tv_title);
		tv_content = (TextView) headerView.findViewById(R.id.tv_content);
		tv_reply_num = (TextView) headerView.findViewById(R.id.tv_reply_num);
		ll_container = (LinearLayout) headerView.findViewById(R.id.ll_container);
	}

	@Override
	protected void setListener() {
		titleText.setText("详情");
		titleLeft.setOnClickListener(this);
		titleRight.setVisibility(View.GONE);
		titleRightImg.setImageResource(R.drawable.delete);
		titleRightImg.setOnClickListener(this);
		
		layoutRefresh.setOnStartListener(startListener);
		ll_return_top.setOnClickListener(this);
		layout_comment.setOnClickListener(this);
		layout_zan.setOnClickListener(this);
	}
	
	private void setData() {
		if (user != null && blog.getClient_id().equals(user.getId())) {
			titleRightImg.setVisibility(View.VISIBLE);
		}else 
			titleRightImg.setVisibility(View.GONE);
		ImageUtils.loadAvatar(mContext, blog.getAvatar(), iv_avatar);
		iv_avatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ArrayList<Img> imgs = new ArrayList<Img>();
				String imgurl_detail = blog.getAvatar();
				Img img = new Img(imgurl_detail);
				imgs.add(img);
				
				Intent intent = new Intent();
				intent.setClass(mContext, ShowLargeImageActivity.class);
				intent.putExtra("imgs", imgs);
				intent.putExtra("position", 1);
				mContext.startActivity(intent);
			}
		});
		tv_name.setText(blog.getNickname());

		//2016.10.17 start 修改帖子时间
		tv_date.setText(HemaUtil.transTimeChat(blog.getRegdate())+"发布");
//            tv_date.setText(blog.getRegdate());
		//2016.10.17 end 修改帖子时间
		tv_title.setText(blog.getName());
		//显示帖子内容，并将其中emoji表情进行转换
		HemaUtil.SetMessageTextView(mContext, tv_content, blog.getContent());
		tv_reply_num.setText(blog.getReplycount());
		tvComment.setText(blog.getReplycount());
		
		if (TextUtils.isDigitsOnly(blog.getGoodcount())) {
			goodCount = Integer.parseInt(blog.getGoodcount());
			tvZan.setText(goodCount+"");
		}
		if (blog.getGoodflag().equals("1")) {// 点赞标记	0无 1有
			tvZan.setCompoundDrawablesWithIntrinsicBounds(
					mContext.getResources().getDrawable(R.drawable.thumbs_up_orange), null, null, null);
		}else {
			tvZan.setCompoundDrawablesWithIntrinsicBounds(
					mContext.getResources().getDrawable(R.drawable.thumbs_up_grey), null, null, null);
		}
		addImage();
	}
	
	/**显示发帖人，帖子中的图片
	 * 
	 */
	private void addImage() {
		if (ll_container.getChildCount() > 0) {
			ll_container.removeAllViews();
		}
		
		ArrayList<ImageItem> items = blog.getItems();
		ArrayList<Img> imgs = new ArrayList<Img>();
		for (int i = 0; i < items.size(); i++) {
			Img img = new Img(items.get(i).getimgurlbig());
			imgs.add(img);
			setImages(items.get(i).getimgurlbig(), imgs, i);
		}
	}
	
	private void setImages(String path, final ArrayList<Img> imgs, final int index) {
		View view = LayoutInflater.from(mContext).inflate(
				R.layout.layout_laoke_detail_image, null);
		ImageView imageview = (ImageView) view.findViewById(R.id.imageview);
        int wide = XtomWindowSize.getWidth(mContext) - BaseUtil.dip2px(mContext, 15)*2;
        imageview.getLayoutParams().height = wide*325/585;
		ImageUtils.loadBigImage(mContext, path, imageview);
		imageview.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, ShowLargeImageActivity.class);
				intent.putExtra("imgs", imgs);//所有的图片地址
				intent.putExtra("position", index+1);//当前是第几张图片
				mContext.startActivity(intent);
			}
		});
		ll_container.addView(view);
	}
	
	private OnStartListener startListener = new OnStartListener() {
		
		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			page = 0;
			getReply();
		}
		
		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			page++;
			getReply();
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_btn:
			finish();
			break;
		case R.id.title_right_img:
			HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
            hbDialog.setText("确定删除?");
            hbDialog.setLeftButtonText("取消");
            hbDialog.setRightButtonText("确定");
            hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
            hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

				@Override
				public void onLeftButtonClick(HemaButtonDialog dialog) {
					dialog.cancel();
				}

				@Override
				public void onRightButtonClick(HemaButtonDialog dialog) {
					dialog.cancel();
					getNetWorker().blogSaveoperate(user.getToken(),
							"1", blog.getId());
				}
            	
            });
			break;
		case R.id.ll_return_top:
			listview.setSelection(0);
			break;
		case R.id.layout_zan:
		    if (user != null) {
		        String oper = "1";//    1：添加 ;2：取消 ;3：清空
	            if (blog.getGoodflag().equals("1")) {// 点赞标记    0无 1有
	                oper = "2";
	            }else {
	                oper = "1";
	            }
	            getNetWorker().FolColOperate(user.getToken(), "3", oper, blog_id);
            }else {
                Intent itLogin = new Intent(mContext, LoginActivity.class);
                startActivity(itLogin);
            }
			break;
		case R.id.layout_comment:
            loginCallBack = new LoginUtil.LoginCallBack() {
                @Override
                public void onLogin() {
                    Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
                    itComment.putExtra("type", 2);
                    itComment.putExtra("blog_id", blog_id);
                    startActivity(itComment);
                    loginCallBack = null;
                }
            };
            LoginUtil.getInstance(mContext, loginCallBack);
			break;
		}
	}

    @Override
    public void onClickListener(int position) {
        //当点击某一条评论的时候
    }

    @Override
    public void onReplyClckListener(int position) {
        //跟楼回复
        reply = replies.get(position);
        Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
        itComment.putExtra("type", 2);
        itComment.putExtra("blog_id", blog_id);
        itComment.putExtra("reply", reply);
        startActivity(itComment);
    }

    @Override
    public void onDeleteClckListener(int position) {
        delReply = replies.get(position);
        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
        hbDialog.setText("确定删除评论?");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().delOneReply(user.getToken(), delReply.getId());
            }

        });
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_REPLY_ADD) {
            int replyNum = Integer.parseInt(blog.getReplycount());
            blog.setReplycount(replyNum + 1 + "");
            tvComment.setText(replyNum + 1 + "");
            tv_reply_num.setText(replyNum + 1 + "");
            if (reply != null)
                reply = null;
//			getReply();
			layoutRefresh.getOnStartListener().onStartRefresh(layoutRefresh);
        }else if (msg.getType() == EventBusConfig.UPDATE_REPLY_REMOVE) {

        }
    }
}
